//
// Created by francklinson on 2021/7/6.
//
#include <vector>
#include <string>
#include <unordered_map>
#include <iostream>
#include <unordered_set>
#include <algorithm>

using namespace std;

class Solution {
public:
    /**
     * hash储存{桌号，食物}的数量
     * @param orders
     * @return
     */
    vector<vector<string>> displayTable(vector<vector<string>> &orders) {
        // 从订单中获取餐品名称和桌号，统计每桌点餐数量
        unordered_set<string> foodSets; // 存放食物名字
        unordered_map<int, unordered_map<string, int>> foodsCnt; // 保存桌号及该桌点餐数量，点餐数量也用一个哈希表保存
        for (auto &order:orders) {
            // 添加食物名称
            foodSets.insert(order[2]);
            // 桌号
            int tableNum = stoi(order[1]);
            // 这张桌子上的某样食物数量增加
            ++foodsCnt[tableNum][order[2]];
        }
        // 提取餐品名称，并按字母顺序排列
        int n = (int) foodSets.size();
        vector<string> foodNames;
        for (auto &name:foodSets) {
            foodNames.push_back(name);
        }
        sort(foodNames.begin(), foodNames.end());
        // 提取桌号 按照升序排列
        int m = (int) foodsCnt.size();
        vector<int> tableIds;
        for (auto &x:foodsCnt) {
            tableIds.push_back(x.first);
        }
        sort(tableIds.begin(), tableIds.end());
        // 填写点菜展示表
        vector<vector<string>> ansTable(m + 1, vector<string>(n + 1));
        ansTable[0][0] = "Table";
        // 复制食物名称
        copy(foodNames.begin(), foodNames.end(), ansTable[0].begin() + 1);
        for (int i = 0; i < m; ++i) {
            int id = tableIds[i];
            ansTable[i + 1][0] = to_string(id);
            auto &cnt = foodsCnt[id]; // 这张桌子上每样食物的点餐数目
            for (int j = 0; j < n; ++j) {
                ansTable[i + 1][j + 1] = to_string(cnt[foodNames[j]]);
            }
        }
        return ansTable;

    }
};

int main() {
    vector<vector<string >> orders{{"David",  "3",  "Ceviche"},
                                   {"Corina", "10", "Beef Burrito"},
                                   {"David",  "3",  "Fried Chicken"},
                                   {"Carla",  "5",  "Water"},
                                   {"Carla",  "5",  "Ceviche"},
                                   {"Rous",   "3",  "Ceviche"}};
    Solution sol;
    auto ans = sol.displayTable(orders);
    for (auto &x:ans) {
        for (auto &y:x) {
            cout << y;
            cout <<" ";
        }
        cout << endl;
    }
    return 0;

}
